//
//  GoodsMainViewController.m
//  MyProject
//
//  Created by dllo on 15/10/28.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "GoodsMainViewController.h"
#import "GoodsTopTableViewCell.h"
#import "GoodsTopCollectionViewCell.h"
#import <AFHTTPSessionManager.h>
#import "UIImageView+WebCache.h"
#import "HandleData.h"
#import "Goods.h"
#import "MJRefresh.h"
#import "GoodsWithMessageTableViewCell.h"
#import "GoodsWithMessage.h"
#import "MBProgressHUD.h"
#import "GoodsMessageViewController.h"
#import "GoodsMessageLastViewController.h"
#import "GoodTopLunboCollectionViewCell.h"
#import "GoodsLunBo.h"
#import "GoodsWebViewController.h"
@interface GoodsMainViewController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate>
{
    MBProgressHUD *_hud;
}

@property (nonatomic ,strong) UITableView *tableView;
@property (nonatomic ,strong) NSMutableArray *array;
@property (nonatomic ,strong) NSMutableArray *tableArray;
@property (nonatomic ,strong) UICollectionView *collectionView;
@property (nonatomic ,strong) NSMutableArray *LunboArray;
@property (nonatomic ,strong) NSMutableArray *lunboArr;

@end

@implementation GoodsMainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    [self createTableView];
    [self handleDataToTop];
    [self createCollectionView];
    [self createPage];
    
   // self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:210/255.0 green:255/255.0 blue:255/255.0 alpha:1];
    
   // [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"t2.png"] forBarMetrics:UIBarMetricsDefault];
    
  //  [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    
    //菊花
    _hud = [[MBProgressHUD alloc]initWithFrame:self.view.bounds];
    [self.view addSubview:_hud];
    [_hud show:YES];
    _hud.detailsLabelText = @"加载中...";
    _hud.mode = MBProgressHUDModeIndeterminate;
    _hud.animationType = MBProgressHUDAnimationFade;
    
}

- (void)viewWillAppear:(BOOL)animated
{
    if (![[NSUserDefaults standardUserDefaults]boolForKey:@"isWhite"]) {
        self.tableView.backgroundColor = [UIColor grayColor];
        
        self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
        self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
        
        [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];

    }
    else {
        self.tableView.backgroundColor = [UIColor whiteColor];
        
        self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
        self.navigationController.navigationBar.barTintColor = [UIColor redColor];
        
        [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,nil]];
    }
    self.tabBarController.tabBar.hidden = NO;
    [self saveColor];
    [self.tableView reloadData];
    
}

- (void)recevive:(NSNotification *)noti
{
    [self saveColor];
    [self cahngeColor];
}

- (void)createTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStylePlain];
    [self.tableView registerClass:[GoodsTopTableViewCell class] forCellReuseIdentifier:@"top"];
    [self.view addSubview:_tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[GoodsWithMessageTableViewCell class] forCellReuseIdentifier:@"message"];
    
    
    self.tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height*2/5)];
    [self.tableView addSubview:_tableView.tableHeaderView];
    
}


//轮播图的collectionView
- (void)createCollectionView
{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
    flow.itemSize = CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height*2/5);
    flow.minimumInteritemSpacing = 0;
    flow.minimumLineSpacing = 0;
    flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height*2/5) collectionViewLayout:flow];
    [self.collectionView registerClass:[GoodTopLunboCollectionViewCell class] forCellWithReuseIdentifier:@"collection"];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.tag = 300;
    [self.tableView.tableHeaderView addSubview:_collectionView];
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.bounces = NO;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
    
}

- (void)createPage
{
    UIPageControl *page = [[UIPageControl alloc]initWithFrame:CGRectMake(self.tableView.tableHeaderView.bounds.size.width/2 - 20, self.tableView.tableHeaderView.bounds.size.height - 40, 40, 20)];
    page.numberOfPages = self.LunboArray.count;
    [self.tableView.tableHeaderView addSubview:page];
   // page.backgroundColor = [UIColor redColor];
}

//轮播图

- (void)timer:(NSTimer *)timer
{
    
    UICollectionView *collectionView  = (UICollectionView *)[self.tableView.tableHeaderView viewWithTag:300];
    if ((((NSInteger)collectionView.contentOffset.x) % (NSInteger)(self.view.bounds.size.width)) != 0) {
        [collectionView setContentOffset:CGPointMake(0, 0)];
    }
    if (collectionView.contentOffset.x < collectionView.bounds.size.width * self.LunboArray.count) {
        CATransition *ani = [CATransition animation];
        ani.duration = 3;
        ani.type = @"kCATransitionFade";
        ani.repeatCount = NSIntegerMax;
        [self.collectionView.layer addAnimation:ani forKey:nil];

        [collectionView setContentOffset:CGPointMake(collectionView.contentOffset.x + self.view.bounds.size.width, 0) animated:YES];
    }
    else if (collectionView.contentOffset.x == self.view.bounds.size.width * self.LunboArray.count){
        CATransition *ani = [CATransition animation];
        ani.duration = 3;
        ani.type = @"kCATransitionFade";
        ani.repeatCount = NSIntegerMax;
        [self.collectionView.layer addAnimation:ani forKey:nil];

        collectionView.contentOffset = CGPointMake(0, 0);
        [collectionView setContentOffset:CGPointMake(collectionView.contentOffset.x + self.view.bounds.size.width, 0) animated:YES];
    }
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableArray.count + 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return (self.view.bounds.size.width - 30)/3;
    }
    else{
        if (self.tableArray.count != 0) {
            GoodsWithMessage *message = [self.tableArray objectAtIndex:(indexPath.row - 1)];
            CGRect rect = [message.content boundingRectWithSize:CGSizeMake([UIScreen mainScreen].bounds.size.width - 20, 10000) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14]} context:nil];
            return 51 + [UIScreen mainScreen].bounds.size.width + rect.size.height+20;
        }
        else{
            return 0;
        }
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        GoodsTopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"top"];
        [cell.collectionView registerClass:[GoodsTopCollectionViewCell class] forCellWithReuseIdentifier:@"coll"];
        cell.collectionView.tag = 200;
        cell.collectionView.delegate = self;
        cell.collectionView.dataSource = self;
        cell.collectionView.showsHorizontalScrollIndicator  = NO;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.collectionView reloadData];

        if (![[NSUserDefaults standardUserDefaults]boolForKey:@"isWhite"]) {
            cell.collectionView.backgroundColor = [UIColor grayColor];
        }
        else{
            cell.collectionView.backgroundColor = [UIColor whiteColor];
        }
        return cell;
    }
    else{
        GoodsWithMessageTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"message"];
        if (self.tableArray.count != 0) {
            GoodsWithMessage *message = [self.tableArray objectAtIndex:(indexPath.row - 1)];
            [cell.userImageView sd_setImageWithURL:[NSURL URLWithString:message.avatar1] placeholderImage:[UIImage imageNamed:@"lovebeijing.png"]];
            cell.nameLable.text = message.username;
            cell.timeLable.text = message.datestr;
            [cell.bigImageView sd_setImageWithURL:[NSURL URLWithString:message.url] placeholderImage:[UIImage imageNamed:@"lovebeijing.png"]];
            cell.messageLable.numberOfLines = 0;
            cell.messageLable.text = message.content;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            cell.backgroundColor = [UIColor clearColor];
            if (![[NSUserDefaults standardUserDefaults]boolForKey:@"isWhite"]) {
                cell.messageLable.textColor = [UIColor whiteColor];
                cell.nameLable.textColor = [UIColor whiteColor];
                cell.timeLable.textColor = [UIColor whiteColor];
            }
            else{
                cell.messageLable.textColor = [UIColor blackColor];
                cell.nameLable.textColor =[UIColor blackColor];
                cell.timeLable.textColor = [UIColor blackColor];
            }
        }
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    GoodsMessageLastViewController *goodVC = [[GoodsMessageLastViewController alloc]init];
    [self.navigationController pushViewController:goodVC animated:YES];
    
    if (self.tableArray.count != 0) {
        GoodsWithMessage *goods = [self.tableArray objectAtIndex:(indexPath.row - 1)];
        goodVC.good = goods;
        goodVC.nameId = goods.nameId;
    }
}






//collectionView

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (collectionView.tag == 200) {
        return self.array.count;
    }
    else{
        return self.LunboArray.count + 2;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (collectionView.tag == 200) {
         GoodsTopCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"coll" forIndexPath:indexPath];
        Goods *goods = [self.array objectAtIndex:indexPath.item];
        [cell.topImageView sd_setImageWithURL:[NSURL URLWithString:goods.pic1] placeholderImage:[UIImage imageNamed:@"lovebeijing.png"]];
               return cell;
    }
    else{
        GoodTopLunboCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collection" forIndexPath:indexPath];
        if (self.LunboArray.count != 0) {
            NSMutableArray *arr = [NSMutableArray array];
            arr = [NSMutableArray arrayWithArray:self.LunboArray];
            [arr addObject:[self.LunboArray firstObject]];
            
            NSMutableArray *array = [NSMutableArray array];
            [array addObject:[self.LunboArray lastObject]];
            
            [array addObjectsFromArray:arr];
            
            
            self.lunboArr = [NSMutableArray array];
            [self.lunboArr addObjectsFromArray:array];
            
            GoodsLunBo *lunbo = [array objectAtIndex:indexPath.item];
           // NSLog(@"%d",array.count);
            [cell.topLunBoImageView sd_setImageWithURL:[NSURL URLWithString:lunbo.photo] placeholderImage:[UIImage imageNamed:@"lovebeijing.png"]];
        }
        return cell;
    }
}

//collection 的点击方法:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView.tag == 200) {
        GoodsMessageViewController *goodsVC  = [[GoodsMessageViewController alloc]init];
        [self.navigationController pushViewController:goodsVC animated:YES];
        Goods *goods = [self.array objectAtIndex:indexPath.item];
        goodsVC.Id = goods.nameId;
        NSLog(@"%@",goodsVC.Id);
    }
    //轮播图:
    else{
        GoodsWebViewController *goods = [[GoodsWebViewController alloc]init];
        [self.navigationController pushViewController:goods animated:YES];
        goods.goods = [self.lunboArr objectAtIndex:indexPath.item];
    }
}

- (void)handleDataToTop
{
    NSString *str = @"http://open4.bantangapp.com/community/post/editorRec?client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=1115876&oauth_token=08e623418ebf12fe438fb9eed5d176da&track_deviceid=864516020760583&track_device_info=SM701&channel_name=UMENG_CHANNEL&app_installtime=1438818737013&app_versions=4.1.1&os_versions=4.4.2&screensize=1080&v=6&page=0&pagesize=10";
    
    [HandleData handleDataWithUrl:str completion:^(id data) {
        NSArray *arr = [[data objectForKey:@"data"] objectForKey:@"subject"];
        NSMutableArray *arrMutableArr = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            Goods *goods = [[Goods alloc]init];
            [goods setValuesForKeysWithDictionary:dic];
            [arrMutableArr addObject:goods];
        }
        self.array  = [NSMutableArray arrayWithArray:arrMutableArr];
        [self.tableView reloadData];
        //  NSLog(@"%@",self.array);
        
        NSArray *arr1 = [[data objectForKey:@"data"] objectForKey:@"list"];
        NSMutableArray *tableViewMutableArr = [NSMutableArray array];
        for (NSDictionary *dic1 in arr1) {
            GoodsWithMessage *goods = [[GoodsWithMessage alloc]init];
            [goods setValuesForKeysWithDictionary:dic1];
            [tableViewMutableArr addObject:goods];
        }
        self.tableArray  = [NSMutableArray arrayWithArray:tableViewMutableArr];
        //轮播数据:
        NSArray *arrL = [[data objectForKey:@"data"] objectForKey:@"banner"];
        
        NSMutableArray *arrayL = [NSMutableArray array];
        for (NSDictionary *dicL in arrL) {
            GoodsLunBo *goodL = [[GoodsLunBo alloc]init];
            [goodL setValuesForKeysWithDictionary:dicL];
            [arrayL addObject:goodL];
        }
        self.LunboArray = [NSMutableArray arrayWithArray:arrayL];
        NSLog(@"%@",self.LunboArray);
        

           if (self.tableArray.count != 0) {
            _hud.hidden = YES;
        }
        [self.collectionView reloadData];
        [self.tableView reloadData];
    }];

       [self refresh];
}

- (void)refresh
{
  self.tableView.header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
      NSString *str = @"http://open4.bantangapp.com/community/post/editorRec?client_id=bt_app_android&client_secret=ffcda7a1c4ff338e05c42e7972ba7b8d&track_user_id=1115876&oauth_token=08e623418ebf12fe438fb9eed5d176da&track_deviceid=864516020760583&track_device_info=SM701&channel_name=UMENG_CHANNEL&app_installtime=1438818737013&app_versions=4.1.1&os_versions=4.4.2&screensize=1080&v=6&page=0&pagesize=10";
      
      [HandleData handleDataWithUrl:str completion:^(id data) {
          NSArray *arr = [[data objectForKey:@"data"] objectForKey:@"subject"];
          NSMutableArray *arrMutableArr = [NSMutableArray array];
          for (NSDictionary *dic in arr) {
              Goods *goods = [[Goods alloc]init];
              [goods setValuesForKeysWithDictionary:dic];
              [arrMutableArr addObject:goods];
          }
          self.array  = [NSMutableArray arrayWithArray:arrMutableArr];
          [self.tableView reloadData];
          //  NSLog(@"%@",self.array);
          NSArray *arr1 = [[data objectForKey:@"data"] objectForKey:@"list"];
          NSMutableArray *tableViewMutableArr = [NSMutableArray array];
          for (NSDictionary *dic1 in arr1) {
              GoodsWithMessage *goods = [[GoodsWithMessage alloc]init];
              [goods setValuesForKeysWithDictionary:dic1];
              [tableViewMutableArr addObject:goods];
          }
          self.tableArray  = [NSMutableArray arrayWithArray:tableViewMutableArr];
          if (self.tableArray.count != 0) {
              _hud.hidden = YES;
          }
           [self.collectionView reloadData];
          [self.tableView reloadData];
          [self.tableView.header endRefreshing];
      }];
  }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
